package sample.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.crawler.base.BaseTask;
import sample.enums.MapType;
import sample.model.Company;
import sample.utils.IndexUtils;
import sample.utils.LogUtils;
import sample.utils.StringUtils;

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class M360Task extends BaseTask {




    public M360Task()
    {
        super.mapCode = MapType.m360.getCode();
    }

    public M360Task(String url)
    {
        super.mapCode = MapType.m360.getCode();
        this.url = url;
    }

    @Override
    public String getUrl(Integer pageNo) {
        //return "https://restapi.map.so.com/newapi?brand_cpc=on&keyword="+keywords+"&cityname="+area+"&batch="+pageNo+"&number="+pageSize+"&scheme=https&sid=1000&mobile=1";
        return url.replace("{keyword}",keywords).replace("{cityname}", area).replace("{batch}", pageNo.toString()).replace("{number}", pageSize.toString());
    }

    @Override
    public Integer getTotalCount(JSONObject res) {
        return res.getInteger("totalcount");
    }

    @Override
    public void fillTable(JSONObject res) throws Exception {
        if(!"E0".equals(res.getString("status"))) {
            LogUtils.logger.info("[{}] errors:{}", mapCode, res);
            throw new Exception("360异常");
        }
        JSONArray results = res.getJSONArray("poi");
        if(results == null)
        {
            throw new Exception("no records");
        }
        for (Object o : results) {
            JSONObject target = (JSONObject) o;

            // 过滤排除关键字
            String name = target.getString("name");
            if(StringUtils.contains(name, exclusiveWords)) {
                continue;
            }

            // 过滤空电话
            JSONArray tels = target.getJSONArray("tels");
            String tel = tels == null ? "" : Stream.of(tels.toArray()).map(x->x.toString()).collect(Collectors.joining(";"));
            if(filterTel && StringUtils.isEmpty(tel)) {
                continue;
            }

            StringBuffer locsb = new StringBuffer().append(target.getString("x")).append(",").append(target.getString("y"));

            qrTable.getItems().add(new Company(IndexUtils.getIndex() + "", tel , name, target.getString("province")+ target.getString("city") +target.getString("area"), target.getString("address"), target.getString("type"),
                    keywords, MapType.map.get(mapCode), locsb.toString()));

        }
    }


}
